package yiran.itemuse.listener;

import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.inventory.ItemStack;
import me.clip.placeholderapi.PlaceholderAPI;
import yiran.itemuse.data.ItemCommandService;
import yiran.itemuse.Itemuse;

public class ItemUseListener implements Listener {

    private final ItemCommandService commandService = new ItemCommandService();
    private final Itemuse plugin;

    public ItemUseListener(Itemuse plugin) {
        this.plugin = plugin;
    }

    @EventHandler
    public void onItemUse(PlayerInteractEvent event) {
        Player player = event.getPlayer();
        ItemStack item = event.getItem();

        if (item == null) return;

        ItemCommandService.CommandData data = commandService.getCommandDataByItem(item);
        if (data == null) return;

        // 处理变量占位符
        String command = data.getCommand();

        // 基础变量替换
        command = command
            .replace("%player%", player.getName())
            .replace("%uuid%", player.getUniqueId().toString())
            .replace("%world%", player.getWorld().getName())
            .replace("%x%", String.valueOf(player.getLocation().getBlockX()))
            .replace("%y%", String.valueOf(player.getLocation().getBlockY()))
            .replace("%z%", String.valueOf(player.getLocation().getBlockZ()));

        // PlaceholderAPI 支持
        if (plugin.getServer().getPluginManager().isPluginEnabled("PlaceholderAPI")) {
            command = PlaceholderAPI.setPlaceholders(player, command);
        }

        // 使用控制台执行命令
        String finalCommand = command;
        Bukkit.getScheduler().runTask(plugin, () -> {
            Bukkit.dispatchCommand(Bukkit.getConsoleSender(), finalCommand);
        });

        // 消耗物品
        if (data.shouldConsume()) {
            if (item.getAmount() > 1) {
                item.setAmount(item.getAmount() - 1);
            } else {
                player.getInventory().setItemInMainHand(null);
            }
        }
    }
}



